package com.jzy.gulimall.cart.interceptor;

import cn.hutool.core.lang.UUID;
import com.jzy.common.constant.AuthServerConstant;
import com.jzy.common.constant.CartConstant;
import com.jzy.common.utils.CookieUtil;
import com.jzy.common.vo.MemberRespVo;
import com.jzy.gulimall.cart.vo.UserInfoTo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author jzy
 * @date 2020/9/18 14:30
 * 判断用户登录状态
 */
public class CartInterceptor implements HandlerInterceptor {

    //同一个线程共享数据 多个线程多个副本
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();
    /**
     *  在目标方法执行之前拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberRespVo attribute = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute != null) {
            //用户登录
            userInfoTo.setUserId(attribute.getId());
        }
        String userKey = CookieUtil.getCookieValue(request, CartConstant.TEMP_USER_COOKIE_NAME, false);
        if (StringUtils.isNotBlank(userKey)) {
            userInfoTo.setUserKey(userKey);
            userInfoTo.setTempUser(true);
        } else {
            userInfoTo.setUserKey(UUID.randomUUID().toString(true));
        }
        threadLocal.set(userInfoTo);
        return true;
    }

    /**
     *  在目标方法执行之前后
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        if (!userInfoTo.isTempUser()) {
            //让浏览保存临时用户
            CookieUtil.setCookie(request,response,CartConstant.TEMP_USER_COOKIE_NAME,userInfoTo.getUserKey(),CartConstant.TEMP_USER_COOKIE_TIMEOUT,false,"gulimall.com");
        }
    }
}
